import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hygf/bean/customer_detail.dart';
import 'package:hygf/page/home/customer_detail/check_accept/view.dart';
import 'package:hygf/page/home/customer_detail/explore_msg/view.dart';
import 'package:hygf/page/home/customer_detail/start_approval/logic.dart';
import 'package:hygf/page/home/customer_detail/start_approval/view.dart';
import 'package:map_launcher/map_launcher.dart';

import '../../../bean/CustomerList.dart';
import '../../../config/ApiConfig.dart';
import '../../../config/StyleConfig.dart';
import '../../../http/DioClient.dart';
import '../../../http/core/ResponseData.dart';
import '../../../res/HDColors.dart';
import '../../../util/HDNavigator.dart';
import '../../../util/LoadingUtils.dart';
import '../../../view/common_widget.dart';
import 'base_msg/view.dart';
import 'check_accept/logic.dart';
import 'construct_msg/logic.dart';
import 'construct_msg/view.dart';
import 'design_msg/logic.dart';
import 'design_msg/view.dart';
import 'explore_msg/logic.dart';
import 'net_msg/logic.dart';
import 'net_msg/view.dart';

class CustomerDetailPage extends StatefulWidget {
  CustomerDetailPage({Key? key}) : super(key: key);

  @override
  State<CustomerDetailPage> createState() => CustomerDetailPageState();
}

class CustomerDetailPageState extends State<CustomerDetailPage>
    with TickerProviderStateMixin {
  int currentIndex = 0;
  String title = "客户详情";
  CustomerListItem customerListItem = CustomerListItem();
  var address = "".obs;
  var addressLong = "".obs;
  var addressLat = "".obs;

  var conAddress = "".obs;
  var conAddressLong = "".obs;
  var conAddressLat = "".obs;
  ReconnaissanceLink reconnaissanceLink = ReconnaissanceLink();

  Widget exploreMsgPageGetX = GetBuilder<RefreshTabLogic>(
      tag: "1",
      builder: (logic) {
        return ExploreMsgPage();
      });
  Widget designMsgPageGetX = GetBuilder<RefreshTabLogic>(
      tag: "2",
      builder: (logic) {
        return DesignMsgPage();
      });
  Widget startApprovalPageGetX = GetBuilder<RefreshTabLogic>(
      tag: "3",
      builder: (logic) {
        return StartApprovalPage();
      });
  Widget constructMsgPageGetX = GetBuilder<RefreshTabLogic>(
      tag: "4",
      builder: (logic) {
        return ConstructMsgPage();
      });
  Widget netMsgPageGetX = GetBuilder<RefreshTabLogic>(
      tag: "5",
      builder: (logic) {
        return NetMsgPage();
      });
  Widget checkAcceptPageGetX = GetBuilder<RefreshTabLogic>(
      tag: "6",
      builder: (logic) {
        return CheckAcceptPage();
      });

  String url = "";
  final List<BadgeTab> tabs = [];
  late TabController tabController;
  final List<Widget> pageList = [];

  @override
  initState(){
    var map = Get.arguments;
    title = map["title"] ?? "客户详情";
    tabs.add(BadgeTab(text: "基础信息"));
    tabs.add(BadgeTab(text: "踏勘信息"));
    tabs.add(BadgeTab(text: "设计图纸"));
    tabs.add(BadgeTab(text: "开工报审"));
    tabs.add(BadgeTab(text: "施工环节"));
    tabs.add(BadgeTab(text: "并网环节"));
    tabs.add(BadgeTab(text: "验收环节"));

    pageList.add(BaseMsgPage());
    pageList.add(exploreMsgPageGetX);
    pageList.add(designMsgPageGetX);
    pageList.add(startApprovalPageGetX);
    pageList.add(constructMsgPageGetX);
    pageList.add(netMsgPageGetX);
    pageList.add(checkAcceptPageGetX);
    tabController = TabController(length: tabs.length, vsync: this);
    tabController.addListener(() {});
    // 更新tabBar
    Get.put(tag: "1", RefreshTabLogic());
    Get.put(tag: "2", RefreshTabLogic());
    Get.put(tag: "3", RefreshTabLogic());
    Get.put(tag: "4", RefreshTabLogic());
    Get.put(tag: "5", RefreshTabLogic());
    Get.put(tag: "6", RefreshTabLogic());
    if (map["pageData"] != null) {
      customerListItem = map["pageData"];
      requestData();
      if (map["title"] != null) {
        if (map["title"] == "踏勘详情") {
          tabController.index = 0;
        }
        if (map["title"] == "待踏勘") {
          tabController.index = 1;
        }
      } else {
        if (customerListItem.status == 3 ||
            customerListItem.status == 4 ||
            customerListItem.status == 6) {
          title = "踏勘提交";
          tabController.index = 1;
        }
        if (customerListItem.status == 11 ||
            customerListItem.status == 12 ||
            customerListItem.status == 14) {
          title = "开工报审提交";
          tabController.index = 3;
        } else if (customerListItem.status == 7) {
          title = "设计待审核";
          tabController.index = 2;
        } else if (customerListItem.status == 15 ||
            customerListItem.status == 16 ||
            customerListItem.status == 18) {
          title = "施工提交";
          tabController.index = 4;
        } else if (customerListItem.status == 19 ||
            customerListItem.status == 20 ||
            customerListItem.status == 22) {
          title = "并网提交";
          tabController.index = 5;
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          HDNavigator.close(result: "refresh");
          return false;
        },
        child: Scaffold(
          appBar: AppBar(
              title: Text(title),
              elevation: 0,
              backgroundColor: HDColors.green,
              actions: [
                Visibility(
                    visible: false,
                    child: TextButton(
                        onPressed: () {},
                        child: const Text("删除",
                            style: TextStyle(
                                color: HDColors.white,
                                fontSize: StyleConfig.fontContentSize14)))),
              ],
              leading: CommonWidget.getAppBarLeading()),
          body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            buildTop(),
            CommonWidget.tabBar(tabController, tabs,
                labelColor: HDColors.blue, indicatorColor: HDColors.blue),
            Expanded(
                child: TabBarView(
                    physics: NeverScrollableScrollPhysics(), //禁止滑动
                    controller: tabController,
                    children: pageList))
          ]),
        ));
  }

  buildTop() {
    return Card(
      margin: EdgeInsets.fromLTRB(20, 15, 20, 15),
      color: HDColors.white,
      shadowColor: Colors.white,
      elevation: 0,
      shape: RoundedRectangleBorder(
          side: BorderSide(width: 0.3, color: HDColors.divider),
          borderRadius: BorderRadius.all(new Radius.circular(5))),
      child: Container(
          width: double.infinity,
          height: 145,
          child:Stack(children: [
                Container(
                  margin: EdgeInsets.fromLTRB(20, 15, 20, 0),
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(5.0),
                      child: Stack(
                        alignment: Alignment.topCenter,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Text(
                                "客户姓名:${customerListItem.customerName}",
                                style: const TextStyle(
                                    fontSize: StyleConfig.fontContentSize16,
                                    color: HDColors.formTitleColor),
                              ),
                              SizedBox(
                                height: 5,
                              ),
                              Text(
                                "客户电话:${customerListItem.phoneNumber}",
                                style: const TextStyle(
                                    fontSize: StyleConfig.fontContentSize16,
                                    color: HDColors.formTitleColor),
                              ),
                              SizedBox(
                                height: 5,
                              ),
                               Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Text("踏勘位置:",
                                          style: TextStyle(
                                              fontSize: StyleConfig
                                                  .fontContentSize14,
                                              color: HDColors.siGrayHint)),
                                      Icon(
                                          color: HDColors.blue,
                                          Icons.location_on_outlined),
                                      Expanded(
                                          child: Obx(
                                                  () =>Text(address.value ??
                                                  "暂无位置信息",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                  fontSize: StyleConfig
                                                      .fontContentSize14,
                                                  color: HDColors.siGrayHint)))),
                                    ]),
                              SizedBox(
                                height: 5,
                              ),
                              Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text("施工位置:",
                                        style: TextStyle(
                                            fontSize: StyleConfig
                                                .fontContentSize14,
                                            color: HDColors.siGrayHint)),
                                    Icon(
                                        color: HDColors.blue,
                                        Icons.location_on_outlined),
                                    Expanded(
                                        child: Obx(
                                                () =>Text(conAddress.value ??
                                                "暂无位置信息",
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                    fontSize: StyleConfig
                                                        .fontContentSize14,
                                                    color: HDColors.siGrayHint)))),
                                  ]),
                              SizedBox(
                                height: 5,
                              ),
                              CommonWidget.divider(1),
                            ],
                          )
                        ],
                      )),
                ),
                Positioned(
                    top: 55,
                    right: 10,
                    child: IconButton(
                        onPressed: () {
                          openMapsSheet(context);
                        },
                        icon: Icon(
                          Icons.near_me_rounded,
                          color: HDColors.blue,
                        ))),
                Positioned(
                    bottom: 10,
                    right: 10,
                    child: IconButton(
                        onPressed: () {
                          openMapsSheet(context,isConstruct: true);
                        },
                        icon: Icon(
                          Icons.near_me_rounded,
                          color: HDColors.blue,
                        )))
              ]),)
    );
  }

  void openMapsSheet(BuildContext context, { bool isConstruct = false}) async {
    double latitude = 31.837982;
    double longitude = 117.262904;
    String address = "中科大先进研究院";
    try {
      if (isConstruct) {
        if(conAddressLat.value.isNotEmpty){
          latitude =
              double.parse(conAddressLat.value);
          longitude =
              double.parse(conAddressLong.value);
          address = conAddress.value;
        }
      }else{
        if((reconnaissanceLink.addressLatitude??latitude.toString()).isNotEmpty){
          latitude =
              double.parse(reconnaissanceLink.addressLatitude??latitude.toString());
          longitude =
              double.parse(reconnaissanceLink.addressLongitude??longitude.toString());
          address = reconnaissanceLink.address?? "中科大先进研究院";
        }
      }
      final availableMaps = await MapLauncher.installedMaps;
      await availableMaps.first.showMarker(
        coords: Coords(latitude, longitude),
        title: address,
      );
    } catch (e) {
      print("openMapsSheet error is ${e}");
    }
  }

  Future<void> requestData() async {
    ResponseData responseData = await DioClient().doPost(
        ApiConfig.customerDetail,
        data: {
          "id": customerListItem.id,
          "customerInfoId": customerListItem.customerInfoId
        },
        options: Options(extra: {"hideLoading": true}));
    LoadingUtils.dismiss();
    if (responseData.isok) {
      if (responseData.code == "0") {
        CustomerDetail entity = CustomerDetail.fromJson(responseData.data);
        Get.put(ExploreMsgLogic()).setData(entity.reconnaissanceLink);
        Get.put(DesignMsgLogic()).setData(entity.designDrawLink);
        Get.put(StartApprovalPageLogic()).setData(entity.startedApproval);
        Get.put(ConstructMsgLogic()).setData(entity.constructionLink);
        Get.put(CheckAcceptLogic()).setData(entity.acceptanceLink);
        Get.put(NetMsgLogic()).updatePage(entity.gridConnectedLink);
        if (entity.reconnaissanceLink != null) {
          reconnaissanceLink = entity.reconnaissanceLink!;
          address.value = reconnaissanceLink.address ?? "";
          addressLong.value = reconnaissanceLink.addressLongitude ?? "";
          addressLat.value = reconnaissanceLink.addressLatitude ?? "";
        }
        if (entity.constructionLink != null) {
          conAddress.value = entity.constructionLink!.address ?? "";
          conAddressLong.value = entity.constructionLink!.addressLongitude ?? "";
          conAddressLat.value = entity.constructionLink!.addressLatitude ?? "";
        }
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    LoadingUtils.dismiss();
  }
}

// 更新tabBar
class RefreshTabLogic extends GetxController {
  RefreshTabLogic();

  refreshTabBar() {
    update();
  }
}
